package com.linzm.leetcode.primary.哈希表.两个数组的交集;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zimingl
 * @Date 2022/10/6 23:40
 * @Description: TODO
 */
public class 哈希表1两数之和 {

    public int[] twoSum(int[] nums, int target) {
        if (nums == null || nums.length == 0){
            return new int[0];
        }
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])){
                res[1] = i;
                res[0] = map.get(target - nums[i]);
            }
            map.put(nums[i], i);
        }
        return res;
    }

    @Test
    public void test(){
       int[] nums = new int[]{2, 7, 11, 15};
       int target = 9;
       twoSum(nums, target);
    }

    private static int[] twoSum2(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[target - i])){
                nums[1] = i;
                nums[0] = map.get(target - nums[i]);
            }
            map.put(nums[i], i);
        }
        return result;
    }

}
